<?php

# 助手函数
# if(!function_exists('funcxxx')){ }

// 异常中断
function abort($message, $code=0){
    global $_cbase; // Exception 前/后 trace的信息不一样，放前面更能准确提示
    $_cbase['_trace'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 8);
    throw new Exception($message, $code);
}

// dump(格式化输出：变量，数组，Object)
function dump(...$args){
    Debug::dump($args, '');
}
function read($fp, $dir='config'){
    static $sy_mods;
    if(empty($sy_mods)){ $sy_mods = include DIR_APP."/config/sy_mods.php"; }
    if($fp=='sy_mods'){ return $sy_mods; }
    $file = isset($sy_mods[$fp]) ? "/dic/_$fp.php" : "/$dir/$fp.php";
    $root = $dir=='xtab' ? DIR_DATA : DIR_APP;
    if(!file_exists($root.$file)){ abort("Config `$file` NOT Found.", 688); }
    return require $root.$file;
}
function db($dbkey=''){
    return Dbop::db($dbkey); 
}
function data($mod, $whr='', $lmt='10', $ord='', $ops=[]){
    return Dbop::data($mod, $whr, $lmt, $ord, $ops);
}

function vmode() {
    global $_cbase; $tmode = $_cbase['vmode']; $mkvs = $_cbase['mkvs'];
    if(empty($mkvs['part'])){ return ''; }
    $vmode = isset($tmode[$mkvs['part']]) ? $tmode[$mkvs['part']] : $tmode['_def_'];
    return $vmode;
}
function uval($key, $def='', $from='gp'){ // GET/POST,SERVER,
    if($from=='gp'){
        if(isset($_GET[$key])){
            $val = $_GET[$key];
        }elseif(isset($_POST[$key])){
            $val = $_POST[$key];    
        }else{
            $val = $def;
        }
    }else{
        $val = isset($_SERVER[$key]) ? $_SERVER[$key] : $def;
    }
    if(is_string($val)){ str_replace(["'",'"','<','>'], '', $val); }
    return $val;
} 

// 获取客户端IP地址 (xf=::1;ra=192.168.0.1,192.168.0.1;cip=127.0.0.1)
function ip($flag=0){
    return Basic::envIP();
}

function path($path=1){
    // $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    global $_cbase; $paths = $_cbase['paths']; $vroot = $_cbase['vroot'];
    if(isset($vroot[$path])){
        $path = $vroot[$path];
    }elseif(isset($paths[$path])){
        $path = $paths[$path];
    }elseif($path=='d'){
        return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'];
    }elseif(strpos($path,':')){ // path('api:demo.1234') -> /api.php/demo.1234
        $tmp = explode(':', $path); $vroot = isset($vroot[$tmp[0]]) ? $vroot[$tmp[0]] : "/{$tmp[0]}.php?r=";
        $path = $vroot . $tmp[1];
    }else{                      // path('demo.1234')   -> /index.php/demo.1234
        $path = $vroot[1].$path;
    }
    return $_cbase['webRoot'].$path; 
}
function tpl_path($tpl, $ext=''){
    global $_cbase; $mkvs = $_cbase['mkvs'];
    if(!$tpl){ return ''; }
    if(substr_count($tpl,'/')==1){
        $tpl = "{$mkvs['part']}/$tpl";
    }elseif(!strpos($tpl,'/')){ 
        $tpl = "{$mkvs['part']}/{$mkvs['mod']}/$tpl";
    }
    $tpext = $ext ? substr($tpl,0-strlen($ext)) : substr($tpl,-4); 
    if(strstr(substr($tpl,-4),'.')){ 
        $ext=''; 
    }elseif($ext){
        if($ext!=$tpext){ $tpl .= $ext; }
    }else{
        if(!in_array($tpext,['.htm','.xml'])){ $tpl .= ".htm"; }
    }
    return $tpl;
}

function md_view($stpl, $retitle=0, $nul404=0){
    $data = Encode::mdView($stpl, $retitle);
    if($nul404 && !$data){ Http::status(404); Http::status(601); }
    return $data;
}

function fix_link($data){
    global $_cbase; $paths = $_cbase['paths'];
    foreach($paths as $pk=>$path){
        $data = str_replace('{='.$pk.'}', path($pk), $data);
    }
    return $data;
}
function jscfg($re='js', $ktb=['ck','vroot']){
    global $_cbase; 
    $res = [];
    foreach($ktb as $kk){ $res[$kk] = $_cbase[$kk]; }
    if($re=='arr'){ return $res; }
    $text = json_encode($res, JSON_UNESCAPED_UNICODE);
    if($re='js'){ $text = "<script>var _cbase = $text;</script>"; }
    echo "$text\n";
}

// 启动session
function sess_on(){
    if(session_status()!==PHP_SESSION_ACTIVE){ 
        session_start(); 
    }
    #session_destroy(); // 销毁session
}

function error_handler_ys($errno, $errmsg, $errfile, $errline) {
    $exrow = ['file'=>$errfile, 'line'=>$errline, 'errmsg'=>$errmsg."({$errno})"];
    $ctrl = new Ctrl();
    $ctrl->error($exrow, 'Handler');
    die();
}

# ////////////////////////////////////

// user function
